<template>
  <div class="app">
    <Header v-if="compareList.length>0" 
      :compareList="compareList"
      @remove="change"
      @compare="showCompare=true"
      />
    <List :list ="list" @change="change"/>
    <Compare v-if="showCompare"
    :compareList="compareList"
    @close="showCompare = false"
    />
  </div>
</template>

<script>
import Header from './components/Header.vue'
import List from './components/List.vue'
import Compare from './components/Compare.vue'
import axios from 'axios';
export default {
  data() {
    return {
      list:[],
      compareList:[],
      showCompare:false
    }
  },
  created() {
    this.getList()
  },  
  methods:{
    async getList() {
      try {
        const res = await axios.get('https://zyxcl.xyz/exam_api/bottle')
        this.list = res.data.value
      }catch(e){
        console.log(e)
      }
    },
   change(title) {
      // 根据title先找下标
      const index = this.list.findIndex(v=>v.title === title)
      // 判断超过三个并且当前点击的元素没有选中  就停止执行
      if(this.compareList.length>=3 && !this.list[index].checked) {
        return
      }
      // 添加新属性
      // this.list[index].checked = !this.list[index].checked
      this.$set(this.list[index] , 'checked' , !this.list[index].checked)
      if(this.list[index].checked) {
        // 选中添加到头部
        this.compareList.push(this.list[index])
      }else{
        // 取消则从头部删除
        this.compareList = this.compareList.filter(v => v.title!==title)
      }
    }
  },
  components:{
    Header,
    List,
    Compare
  }
}
</script>

<style lang="scss">
  .app {
  padding: 70px 0;
  width: 100vw;
  height: 100vh;
  overflow: auto;
  background: #2a2b2f;
}
</style>
